﻿using System;
using System.IO;
using System.IO.Pipes;
using System.Threading;

namespace CgdataBase
{
    public class CnsosClientHelper
    {
        private const string PipeName = "CnsosNet";

        public static string GetUsername()
        {
            try
            {
                using (var pipeClient = new NamedPipeClientStream(".", PipeName, PipeDirection.InOut))
                {
                    pipeClient.Connect(100);
                    LogHelper.Info("Connected to pipe.");

                    using StreamReader sr = new StreamReader(pipeClient);
                    using StreamWriter sw = new StreamWriter(pipeClient);
                    sw.AutoFlush = true;
                    sw.WriteLine("GetUsername");
                    Thread.Sleep(1);
                    var username = sr.ReadLine();

                    return username;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Warn(ex);
            }

            return null;
        }

        public static string GetAppVersion(string appName, string appVersion)
        {
            try
            {
                using (var pipeClient = new NamedPipeClientStream(".", PipeName, PipeDirection.InOut))
                {
                    pipeClient.Connect(100);
                    LogHelper.Info("Connected to pipe.");

                    using StreamReader sr = new StreamReader(pipeClient);
                    using StreamWriter sw = new StreamWriter(pipeClient);
                    sw.AutoFlush = true;
                    sw.WriteLine($"GetAppVersion,{appName},{appVersion}");
                    Thread.Sleep(1);
                    var version = sr.ReadLine();

                    return version;
                }
            }
            catch (Exception ex)
            {
                LogHelper.Warn(ex);
            }

            return null;
        }
    }
}